package com.atguigu.netty.simple;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClient {

    private static Logger logger = LoggerFactory.getLogger(Thread.currentThread().getClass());

    public static void main(String[] args) {

        // 客户端需要一个时间循环组
        NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            // 创建客户端启动对象
            // 客户端使用Bootstrap
            Bootstrap bootstrap = new Bootstrap();

            // 设置参数
            bootstrap.group(eventLoopGroup) // 设置线程组
                    .channel(NioSocketChannel.class) // 设置客户端通道实现类（反射）
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyClientHandler());
                        }
                    });

            logger.info("客户端 ok。。。。。");

            // 启动客户端连接服务端
            // ChannelFuture设置netty的异常模型
            // 直到连接返回，才会继续后面的执行，否则阻塞当前线程
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();

            //直到channel关闭，才会继续后面的执行，否则阻塞当前线程
            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
